// 工具函数
import Vue from 'vue'

// 深拷贝
function deepCopy <T>(data:T):T {

    if( typeof data != "object" ){
        return data ;
    }  

    let newObj:any = Array.isArray(data) ? [] : {};  //开辟一块新的内存空间

    for( var i  in  data ) {
        newObj[i] = deepCopy ( data [i] );           //通过递归实现深层的复制 
    }

　　return newObj;
    
}

/*
**  提取对象值
**  @params 
        source: 被提取对象
        target: 赋值对象
*/
function objecGetValue <T>(source:any, target:T):T {

    Object.keys(target).forEach(key =>{

        if(source.hasOwnProperty(key)){
            target[key] = source[key] !== undefined ? source[key] : target[key];
        }

    })
    return target;
}

interface EnumParams{
    [propName:string]: number
}
interface Enum{
    [propName:string]: string | number
}

// 构建枚举
function creatEnum(data:EnumParams|string[]):Enum {
    let cache:Enum = {}
    if((<string[]>data).length){
        (<string[]>data).forEach((key, index) =>{
            if(key){
                cache[cache[key] = index] = key;
            }
            
        })
    }else{

        Object.keys(data).forEach(key =>{
            cache[cache[key] = data[key]] = key;
        })
        
    }      
    
    return cache;
}

// 样式单位转换( px 转 rem )
function pxToRem (size:number):number{
    return size/14;
}

//是否为空对象
function isEmptyObj(data:any):boolean{
    return JSON.stringify(data) === "{}"
}

//值是否为对象
function isObj(data:any):boolean{
    return data.toString() === '[object Object]'
}

/*
** 获取元素内容并 聚焦该元素（ 剪贴板功能 ）
** @params
        element: 触发对象
*/

function select(element) {
    var selectedText;

    if (element.nodeName === 'SELECT') {
        element.focus();

        selectedText = element.value;
    }
    else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
        var isReadOnly = element.hasAttribute('readonly');

        if (!isReadOnly) {
            element.setAttribute('readonly', '');
        }

        element.select();
        element.setSelectionRange(0, element.value.length);

        if (!isReadOnly) {
            element.removeAttribute('readonly');
        }

        selectedText = element.value;
    }
    else {
        if (element.hasAttribute('contenteditable')) {
            element.focus();
        }

        var selection = window.getSelection();
        var range = document.createRange();

        range.selectNodeContents(element);
        selection.removeAllRanges();
        selection.addRange(range);

        selectedText = selection.toString();
    }

    return selectedText;

}

// 复制元素内容到剪贴板
function copyTxt(ele):string{
    
    let txt = select(ele) || '';
    
    try{
        document.execCommand('copy');
    }catch(err){
        throw(`剪贴失败: ${err}`)
    }

    return txt
}

/*
** 日期数据格式化
** @params
        date: 被格式化日期, 默认日期为当天
*/
function formatDate (date?){

    let end = null;
    date = date || new Date();

    if(date){

        let year = date.getFullYear();
        let month = date.getMonth() + 1;
        let day = date.getDate();

        month = month.toString();
        month = month.length <= 1 ?  0 + month : month;

        day = day.toString();
        day = day.length <= 1 ?  0 + day : day;

        end = `${year}-${month}-${day}`;

    }
    return end;
}

/*
** 时间区间, 当前时间 向前或向后
** @params
        data: 以当天未基准， 负值向前取天数， 正值为向后取天数, 
        例如： data = -1 (昨天)  data =1 (明天)
*/ 
function timeInterval (day=1){
    let oneDate = 24*60*60*1000;
    let dateBegin = new Date();
    let dateEnd = new Date();
    
    
    dateBegin.setHours(0,0,0,0)
    dateEnd.setTime(dateBegin.getTime() + oneDate * day)

    if(day < 0){
        [dateBegin, dateEnd] = [dateEnd, dateBegin];
    }
    
    return {
        dateBegin: dateBegin,
        dateEnd: dateEnd
    }
    
}

/*
** 提取v-model参数
** @describe
        用在包装组件中, 提取相应的值和方法
** @params
        context: 组件上下文, 
*/
function extractModel(context){

    let value = context.data.model.value || '';
    let callback = context.data.model.callback || function (){};
    let conf = context.props.conf || {};
        
    return {value, callback, conf}
}


export {
    deepCopy,
    objecGetValue,
    creatEnum,
    pxToRem,
    isEmptyObj,
    isObj,
    copyTxt,
    formatDate,
    timeInterval,
    extractModel,
};


